package com.ninong.ker.admin.rest;

import java.io.IOException;

import com.ninong.ker.admin.service.dto.StorageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ninong.ker.admin.sevice.StorageService;
import com.ninong.ker.common.annotation.log.Log;
import com.ninong.ker.common.annotation.perm.CmdAdmin;
import com.ninong.ker.common.response.CmdResponse;

/**
 * 本地存储管理
 * 
 * @author 鸠摩智
 * @date 2020年12月7日 下午5:07:50
 */
@RestController
@RequestMapping("/cmd/v1/storage")
public class StorageResources {

	@Autowired
	private StorageService storageService;

	/**
	 * 存储列表
	 * 
	 * @param entity
	 * @return
	 */
	@Log("存储列表")
	@CmdAdmin({ "admin", "storage:list" })
	@PostMapping
	public ResponseEntity<CmdResponse> list(@RequestBody StorageDTO entity) {
		CmdResponse response = new CmdResponse();
		response.setData(storageService.listPage(entity));
		return ResponseEntity.ok(response);
	}

	/**
	 * 上传附件
	 * 
	 * @param files
	 * @return
	 */
	@PostMapping(value = "/upload")
	@CmdAdmin({ "admin", "storage:upload" })
	public ResponseEntity<Object> create(@RequestParam("files") MultipartFile[] files) throws IOException {
		CmdResponse response = new CmdResponse();
		response.setData(storageService.create(files));
		return ResponseEntity.ok(response);
	}

	/**
	 * 上传附件
	 * 
	 * @param files
	 * @return
	 */
	@PostMapping(value = "/singleUpload")
	public ResponseEntity<Object> create(@RequestParam MultipartFile files) throws IOException {
		CmdResponse response = new CmdResponse();
		response.setData(storageService.uploadSingleFile(files));
		return ResponseEntity.ok(response);
	}

	/**
	 * 删除附件
	 * 
	 * @param ids
	 * @return
	 */
	@DeleteMapping
	@CmdAdmin({ "admin", "storage:delete" })
	public ResponseEntity<Object> delete(@RequestBody String[] ids) {
		storageService.delete(ids);
		return ResponseEntity.ok(new CmdResponse());
	}

	@Log("删除附件")
	@DeleteMapping(value = "/delete/{id}")
	public ResponseEntity<Object> deleteById(@PathVariable String id) {
		storageService.deleteFileById(id);
		return ResponseEntity.ok(new CmdResponse());
	}

	@Log("删除附件")
	@PostMapping(value = "/deleteByUrl")
	public ResponseEntity<Object> deleteByUrl(@RequestBody StorageDTO entity) {
		storageService.deleteFileByUrl(entity.getUrl());
		return ResponseEntity.ok(new CmdResponse());
	}

}
